<?php

namespace App\Libs;
use Exception;

class CompressLibrary
{
     
    private $src;
    private $image;
    private $imageinfo;
    private $percent;
    private $new_width;
    private $new_height;


    /**
     * 图片压缩
     * @param $src 源图
     * @param float $percent 压缩比例
     */
    public function __construct($src, $percent = 1)
    {
        ini_set('memory_limit', '-1');
        $this->src = $src;
        $this->percent = $percent;
    }


    /**
     * 高清压缩图片
     */
    public function compressImg($scene = null, $width=null, $height=null)
    {
        $this->_openImage($scene, $width, $height);
        $funcs = "image" . $this->imageinfo['type'];
        //png最大10jpg最大100
        $quality = $this->imageinfo['type'] == 'png' ? 7 : 80;
        $funcs($this->image, $this->src, $quality);
    }

    /**
     * 内部：打开图片
     */
    private function _openImage($scene, $width, $height)
    {
        list($width, $height, $type, $attr) = getimagesize($this->src);
        $this->imageinfo = array(
            'width' => $width,
            'height' => $height,
            'type' => image_type_to_extension($type, false),
            'attr' => $attr
        );
        if ($scene && $scene == 'size' && $width) {
            $this->new_width = $size[$scene]['width'];
            $this->new_height = $size[$scene]['height'];
        } else { 
            $this->new_width = $width * $this->percent;
            $this->new_height = $height * $this->percent;
        }
        $fun = "imagecreatefrom" . $this->imageinfo['type'];
        dd($fun);
        $this->image = $fun($this->src);
        $this->_thumpImage();
    }

    /**
     * 内部：操作图片
     */
    private function _thumpImage()
    {
        $image_thump = imagecreatetruecolor($this->new_width, $this->new_height);
        
        //将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度
        imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->imageinfo['width'], $this->imageinfo['height']);

        imagedestroy($this->image);
        $this->image = $image_thump;
    }

    /**
     * 销毁图片
     */
    public function __destruct()
    {
        if (!$this->image) {
            // 如果创建失败，记录错误信息并处理（例如抛出异常或返回错误）
            throw new Exception("无法创建图像资源，文件可能不存在或格式不支持");
            // 或者 return ['error' => '图片处理失败']; 
        }
        imagedestroy($this->image);
    }

}
